//
//  AppDelegate.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/17.
//

import UIKit
import IQKeyboardManagerSwift
import Alamofire

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    var netStatusChange: ((_ reachable: Bool) -> Void)? // 网络状态
    var netManager = NetworkReachabilityManager()       // 网络管理类

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//        UIApplication.shared.statusBarStyle = .lightContent
        self.window = UIWindow(frame: UIScreen.main.bounds)
        configSet()
        self.window?.rootViewController = COStartController()
        window?.makeKeyAndVisible()
        return true
    }

    func configSet(){
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.keyboardDistanceFromTextField = 65
    }
    
    //MARK: -------------- network status change ----------------
    func notifyNetworkStatus(){
        netManager?.startListening(onUpdatePerforming: { status in
            if status == .unknown || status == .notReachable{
                if self.netStatusChange != nil{
                    self.netStatusChange!(false)
                }
            }else{
                if self.netStatusChange != nil{
                    self.netStatusChange!(true)
                }
            }
        })
    }
    
    //MARK: -------------- 更改主控制器 ----------------
    func setRootViewController(){
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        if (feed == true){
            if COUserManager.isLogin() {
                window?.rootViewController = UINavigationController(rootViewController: COHomeViewController())
            } else {
                window?.rootViewController = UINavigationController(rootViewController: COLoginIndexViewController())
            }
        }else{
            XLFullscreenPopGesture.configure() // 初始化侧滑
            if (COUserInfoManager.coUserLogin()){
                COUserInfoManager.coGetInfo()
                print("我的token：----------  \(COUserInfoManager.shared.curUser?.token ?? "")")
                COUserInfoManager.coRouteToTabbar()
                AppPurchaseManager.completeTransactions()
                rongCloudClient()
            }else{
                COUserInfoManager.coRouteToLogin()
            }
        }
    }
    
    func rongCloudClient(){
        COChatMsgManager.shared.initRCIM()
        COChatMsgManager.shared.connectIM()
        let tabbar = UIApplication.shared.getKeyWindow()?.rootViewController as! COBaseTabbarController
        if !tabbar.isMember(of: COBaseTabbarController.self){
            return
        }
        COChatMsgManager.shared.unreadBack = { unreadCount in
            DispatchQueue.main.safeAsync {
                let indexNew = tabbar.viewControllers!.count - 2
                if (unreadCount > 0){
                    tabbar.showBadgeMark(unreadCount, indexNew)
                    UIApplication.shared.applicationIconBadgeNumber = unreadCount
                }else{
                    tabbar.showBadgeMark(0, indexNew)
                    UIApplication.shared.applicationIconBadgeNumber = 0
                }
            }
        }
    }
    
    //MARK: -------------  礼物  ----------
    func getGiftSearchList(){
        COHttpManager.request(target: COBaseApi.giftSearch, modelType: COGiftSearchModel.self) { code, object, success in
            if (object?.gift.count ?? 0 > 0){
                COUserInfoManager.configGiftsData(response: object)
            }
        } failureBlock: { code, msg in
        }
    }
    
    //MARK: ------------- 修改在线状态 status 0在线、1繁忙 ----------
    func changeMyStatusOnline(_ status:Int){
        var params = [String:Any]()
        params["status"]  = status
        COHttpManager.request(target: COBaseApi.consumeOnline(param: params), modelType: CONSObjectModel.self) { code, object, success in
            print("修改成功 -- \(status == 0 ? "在线":"繁忙")")
            if (status == 0){
                kLiveCalling.keySaveToNSDefaults(with: false)
            }else{
                kLiveCalling.keySaveToNSDefaults(with: true)
            }
        } failureBlock: { code, msg in
        }
    }
}

